#include <boost/lexical_cast.hpp>
#include "AbstractDatabase.h" 

/**
 *
 **/
AbstractDatabase::AbstractDatabase(PString host, PString port, PString database, PString username, PString password)
{
    this->dbDriverName = NULL;
	this->port = port;
	this->host = host;
	this->database = database;
	this->username = username;
	this->password = password;
}

/**
 *
 **/
AbstractDatabase::~AbstractDatabase() {
    delete this->dbDriverName;
}

/**
 *
 **/
String AbstractDatabase::getDBDriverName() {
    return *this->dbDriverName;
}

/**
 *
 **/
String AbstractDatabase::getHost() {
    return *this->host;
}

/**
 *
 **/
String AbstractDatabase::getPort() {
    return *this->port;
}

/**
 *
 **/
String AbstractDatabase::getDatabase() {
    return *this->database;
}

/**
 *
 **/
String AbstractDatabase::getUserName() {
    return *this->username;
}

/**
 *
 **/
String AbstractDatabase::getPassword() {
    return *this->password;
}

/**
 *
 **/
void AbstractDatabase::error(char* errmsg, char* param, ...)
{
    //cerr << sprintf(errmsg, param) << endl; // unsafe
}


/**
 *
 **/
TableInfo AbstractDatabase::getTableInfoOf(PString database, PString schema, PString table, int option)
{
	TableInfo tinfo;
	tinfo.hasGeometry = false;
	tinfo.hasSRID = false;
	tinfo.name = *table;
	tinfo.schema = *schema;
	tinfo.database = *database;
	tinfo.tableSize = 10000;
	tinfo.message = "";
	if(this->exists(database, schema, table)	)
	{
		if(option & OPTION_TABLE_INFO || option & OPTION_ALL_INFO)
		{
			PQuery query1 = this->getTableInfoQuery( database, schema, table );
			if(query1->hasMore())
			{
				PDataRow row1 = query1->fetch();
				tinfo.hasGeometry = row1->getFieldValue(0).compare("YES") == 0;
				tinfo.hasSRID     = row1->getFieldValue(1).compare("YES") == 0;
				tinfo.tableSize   = boost::lexical_cast<size_t>(row1->getFieldValue(2));
				tinfo.countRows   = boost::lexical_cast<size_t>(row1->getFieldValue(3));
			}
			delete query1;
		}

		if(option & OPTION_FIELD_LIST || option & OPTION_ALL_INFO)
		{
			PQuery query2 = this->getFieldListQuery( database, schema, table );
			while(query2->hasMore())
			{
				FieldInfo field;
				PDataRow row2 = query2->fetch();
				field.name = row2->getFieldValue(0);
				field.type = row2->getFieldValue(1);

				if(field.type.compare("geometry") == 0)
				{
					tinfo.geometry = field;
				}
				else
				{
					tinfo.fields.push_back(field);
				}
			}
			delete query2;
		}
	}

	return tinfo;
}
